package com.suyx.job.service.impl;


import com.suyx.job.dao.JobInfoRepository;
import com.suyx.job.entity.JobInfo;
import com.suyx.job.entity.Page;
import com.suyx.job.service.IJobInfoService;
import com.suyx.job.service.base.impl.MyServiceImpl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: lanyanhua
 * @Date: 2018/10/18 0018 11:50
 * @Description:
 */
@Slf4j
@Service
public class JobInfoServiceImpl extends MyServiceImpl<JobInfo,Integer> implements IJobInfoService {

    private JobInfoRepository jobInfoRepository;

    @Autowired
    public JobInfoServiceImpl(JobInfoRepository repository) {
        super(repository);
        this.jobInfoRepository = repository;
    }

    @Override
    public Page findJobPage(JobInfo jobInfo,Integer page, Integer limit) {
        return  new Page(
                jobInfoRepository.findAll((Root<JobInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
                    List<Predicate> predicates = new ArrayList<>();
                    if(!StringUtils.isEmpty(jobInfo.getJobName())){
                        predicates.add(cb.like(root.get("jobName").as(String.class), "%"+jobInfo.getJobName() + "%"));
                    }
                    if(!StringUtils.isEmpty(jobInfo.getJobGroup())){
                        predicates.add(cb.equal(root.get("jobGroup").as(String.class), jobInfo.getJobGroup()));
                    }

                    return  query.where(predicates.toArray(new Predicate[0]))
                    		.orderBy(cb.asc(root.get("jobId").as(Integer.class))).getRestriction();
                }, PageRequest.of(page,limit))
        );
    }

    @Override
    public boolean existsByJobNameAndJobGroup(String jobName, String jobGroup) {
        return jobInfoRepository.existsByJobNameAndJobGroup(jobName,jobGroup);
    }

    @Override
    public List<JobInfo> findByJobStatus(int i) {
        return jobInfoRepository.findByJobStatus(i);
    }

}
